package com.sfzd5.UI;

import java.awt.*;
import java.util.LinkedHashSet;
import java.util.Set;

public class VerticalFlowLayout implements LayoutManager2 {
    final private Set<Component> components = new LinkedHashSet<>();
    private int vgap = 0;
    public void setVGap(int vgap) { this.vgap = vgap; }

    @Override public void addLayoutComponent(Component comp, Object constraints) {
        this.components.add(comp);
    }

    /* these 3 methods need to be overridden properly */
    @Override public float getLayoutAlignmentX(Container target) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override public float getLayoutAlignmentY(Container target) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override public void invalidateLayout(Container target) {
        // TODO Auto-generated method stub
    }


    @Override public void addLayoutComponent(String name, Component comp) {
        this.components.add(comp);
    }

    @Override public void layoutContainer(Container parent) {
        int x = 0;
        int y = 0;
        for (Component c : this.components)
        {
            if (c.isVisible())
            {
                Dimension d = c.getPreferredSize();
                c.setBounds(x, y, d.width, d.height);
                y += d.height + this.vgap;
            }
        }
    }

    /* these 3 methods need to be overridden properly */
    @Override public Dimension minimumLayoutSize(Container parent) {
        return new Dimension(100, 100);
    }

    @Override public Dimension preferredLayoutSize(Container parent) {
        int w = 0;
        int h = 0;
        for (Component c : this.components)
        {
            if (c.isVisible())
            {
                Dimension d = c.getPreferredSize();
                w = Math.max(w, d.width);
                h += d.height + this.vgap;
            }
        }
        return new Dimension(w,h);
    }

    @Override public Dimension maximumLayoutSize(Container target) {
        return target.getMaximumSize();
    }

    @Override public void removeLayoutComponent(Component comp) {
        this.components.remove(comp);
    }
}
